﻿@using Gx.Model.ViewModel;
@model LKWarehouseContractDto
@{
    ViewBag.Title = "编辑包仓合同";
    Layout = "~/Views/Shared/InfoMaste.cshtml";
}
<script src="~/Js/Global.js?v=20240706"></script>
<script type="text/javascript">
    $(function () {
        InitStoreTypeCombobox();
        InitStoreAlgorithmCombobox();
        InitCustomer();
        InitWareHouse();
        initDom();
        $('#sbIsByTon').switchbutton({ checked: @Html.Raw(Model.Bill.IsByTon ? "true" : "false") });
        $('#CustomerId').combogrid('setValue', { Id: '@Model.Bill.CustomerId', CustomerName: '@Model.Bill.CustomerName' });
        $('#StoreType').combobox('setValue', @Model.Bill.StoreType);
        $('#StoreAlgorithm').combobox('setValue', @Model.Bill.StoreAlgorithm);
        $('#WareHouseId').combobox('setValue', @Model.Bill.WareHouseId);
    });
    function InitCustomer() {
        $('#CustomerId').combogrid({
            url: "/Customer/GetCustomerPageList",
            method: 'post',
            mode: 'remote',
            pageSize: 15,               //每页显示的记录条数，默认为10
            pageList: [10, 15, 20],       //可以设置每页记录条数的列表
            pagination: true,
            panelWidth: 500,
            toolbar: "#customerselecttoolbar2",
            idField: 'Id',
            textField: 'CustomerCode',
            onSelect: function () {
                var g = $('#CustomerId').combogrid('grid');
                var row = g.datagrid('getSelected');
                $('#CustomerId').combogrid("setValue", row.Id);
                $('#CustomerName').textbox('setValue', row.CustomerName);
            },
            columns: [[
                { field: 'Id', title: 'Id', hidden: true },
                { field: 'CustomerCode', title: '客户编号', width: 120, align: 'right' },
                { field: 'CustomerName', title: '客户名称', width: 150, align: 'right' }
            ]],
            fitColumns: true,
            filter: true,  // 启用搜索框
        });
    }

    //function InitStoreTypeCombobox() {
    //    $('#StoreType').combobox({
    //        url: "/LkGlobal/GetStoreTypeList",
    //        valueField: 'Value',
    //        textField: 'Description',
    //        onSelect: function (rec) {
    //            //$('#StoreType').combobox("setValue", rec.Value);
    //        }
    //    });
    //}

    //function InitStoreAlgorithmCombobox() {
    //    $('#StoreAlgorithm').combobox({
    //        url: "/LkGlobal/GetStoreAlgorithmList",
    //        valueField: 'Value',
    //        textField: 'Description',
    //        onSelect: function (rec) {
    //            //$('#ColdStorage').combobox("setValue", rec.Value);
    //        }
    //    });
    //}

    //function InitWareHouse() {
    //    $('#WareHouseId').combotree({
    //        url: "/LKWareHouse/GetHouseComboxTree",
    //        editable: false,
    //        valueField: 'Id',
    //        textField: 'WareHouseName',
    //        onSelect: function (rec) {
    //        }
    //    });
    //}

    //function InitCostTypesCombogrid(id) {
    //    $("#CostType" + id).combogrid({
    //        //panelWidth: 1200,
    //        idField: 'Id',
    //        textField: 'CostTypeName',
    //        url: '/LKCostTypes/GetLKCostTypes',
    //        method: 'post',
    //        mode: 'remote',
    //        columns: [[
    //            { field: 'Id', title: 'Id', hidden: true },
    //            { field: 'CostTypeName', title: '类型', width: 80, align: 'right' }
    //        ]],
    //        onSelect: function (rowIndex, rowData) {
    //            $("#CostTypeId" + id).val(rowData.Id);//combobox('setValue', rowData.Id);
    //            $("#CostType" + id).combobox('setValue', rowData.CostTypeName);
    //            $("#Unit" + id).textbox('setValue', rowData.UnitName);
    //            $("#Price" + id).numberbox('setValue', rowData.UnitPrice);
    //        },
    //        fitColumns: true,
    //        labelPosition: 'top'
    //    });
    //}



    var alldom = new Array();
    var detaildom = new Array();

    function initDom() {
        $("input[type='hidden'][id^='DomId']").each(function () {
            var d = $(this).val();
            if ($.inArray(d, alldom) === -1) {
                // 如果不存在，则添加到数组中
                alldom.push(d);
            }
        });
        $("input[type='hidden'][id^='DetailDomId']").each(function () {
            var d = $(this).val();
            if ($.inArray(d, detaildom) === -1) {
                detaildom.push(d);
            }
        });

    }

    function addDom() {
        var domId = $("#DomNum").val();
        $.post("/LKWarehouseContract/_AddLKWarehouseContract", { domId: domId }, function (html) {
            $.messager.progress('close');
            $("#costgird").append(html);
            $.parser.parse($("#" + domId));
            $("#DomNum").val(Number(domId) + 1);

            initDom();
            var d = Number(domId);
            if ($.inArray(d, alldom) === -1) {
                // 如果不存在，则添加到数组中
                alldom.push(d);
            }

            InitCostTypesCombogrid(domId);
        });
    }

    function delDom(domId) {
        initDom();
        var deid = $("#CostId" + domId).val();
        alldom = $.grep(alldom, function (value) {
            return value != domId;
        });
        $("#" + domId).remove();
    }


    function editLKWarehouseContract() {
        var validate = $("#fm").form("validate")
        if (!validate) {
            return;
        }

        var data = {
            "Id": $("#Id").val(),
            "IsValid": $("#IsValid").val(),
            "ContractNo": $("#ContractNo").textbox('getValue'),
            "CustomerId": $("#CustomerId").combobox('getValue'),
            "CustomerName": $("#CustomerName").textbox('getValue'),
            "ContractTime": $("#ContractTime").datebox('getValue'),
            "BeginTime": $("#BeginTime").datebox('getValue'),
            "EndTime": $("#EndTime").datebox('getValue'),
            "StoreType": $("#StoreType").combobox('getValue'),
            "StoreAlgorithm": $("#StoreAlgorithm").combobox('getValue'),
            "UnitPrice": $("#UnitPrice").numberbox('getValue'),
            "Number": $("#Number").numberbox('getValue'),
            "Amount": $("#Amount").numberbox('getValue'),
            "IsByTon": $('#sbIsByTon').switchbutton('options').checked,
            "WareHouseId": $("#WareHouseId").numberbox('getValue'),
            "Remark": $("#Remark").val()

        };
        initDom();
        var CostList = new Array();
        alldom.forEach(function (value, index) {
            //console.log(index + ': ' + value);
            var i = value;
            var obj = $("#CostType" + i);
            if (obj.length == 0) {
                return false;
            }
            var costTypeId = obj.combogrid('getValue');
            if ($.trim(costTypeId) == "") {
                return false;
            }
            var Id = $("#CostId" + i).val();
            var ContractId = $("#ContractId" + i).val();
            var CostTypeId = $("#CostType" + i).combobox('getValue');
            var CostType = $("#CostType" + i).combobox('getText');
            var Price = $("#Price" + i).numberbox('getValue');
            var Unit = $("#Unit" + i).textbox('getValue');
            var ContractType = $("#ContractType" + i).val();
            var InStorage = $("#sbInStorage" + i).switchbutton('options').checked;
            var OutStorage = $("#sbOutStorage" + i).switchbutton('options').checked;
            var TransferStorage = $("#sbTransferStorage" + i).switchbutton('options').checked;


            //if (CostType == "" || Price == "" || Unit == "") {
            //    Helper.Show("请检查第" + i + "行费用信息");
            //    return;
            //}
            var cost = {
                "Id": Id,
                "ContractId": ContractId,
                "CostTypeId": CostTypeId,
                "ContractType": ContractType,
                "CostType": CostType,
                "Price": Price,
                "Unit": Unit,
                "InStorage": InStorage,
                "OutStorage": OutStorage,
                "TransferStorage": TransferStorage
            };
            CostList.push(cost);
        });

        var detailList = new Array();
        detaildom.forEach(function (value, index) {
            var i = value;
            var BeginTime = $("#BeginTime" + i).datebox('getValue');
            var EndTime = $("#EndTime" + i).datebox('getValue');
            var UnitPrice = $("#UnitPrice" + i).numberbox('getValue');
            var number = $("#Number" + i).numberbox('getValue');
            var TotalPrice = $("#TotalPrice" + i).numberbox('getValue');
            var OriginalAmount = $("#OriginalAmount" + i).numberbox('getValue');
            var IsBalance = $("#sbIsBalance" + i).switchbutton('options').checked;
            var IsCharge = $("#sbIsCharge" + i).switchbutton('options').checked;

            var detail = {
                "Id": $("#DetailId" + i).val(),
                "ContractId": $("#ContractId" + i).val(),
                "BeginTime": BeginTime,
                "EndTime": EndTime,
                "UnitPrice": UnitPrice,
                "Number": number,
                "TotalPrice": TotalPrice,
                "OriginalAmount": OriginalAmount,
                "IsBalance": IsBalance,
                "IsCharge": IsCharge
            };
            detailList.push(detail);
        });

        $.messager.progress({
            title: '请稍后',
            msg: '数据保存中...',
        });
        window.setTimeout(function () {
            $.ajax({
                url: '/LKWarehouseContract/EditLKWarehouseContract',
                type: "post",
                data: JSON.stringify({ Bill: data, CostList: CostList, DetailList: detailList, AttachmentId: $("#hidFileId").val() }),
                contentType: 'application/json; charset=utf-8',
                success: function (json) {
                    $.messager.progress('close');
                    Helper.Show(json.Msg);
                    if (json.Success) {
                        setTimeout(function () { window.location.href = "/LKWarehouseContract/LKWarehouseContractList"; }, 2000);
                    }
                }
            });
        }, 2000);
    }

    //function checkDecimal(newValue, oldValue) {
    //    if (newValue.toString().split('.').length > 1) {
    //        var decimalPart = newValue.toString().split('.')[1];
    //        if (decimalPart.length > 2) {
    //            //$.messager.alert('Warning', '超过两位小数！');
    //            $(this).numberbox('setValue', oldValue);
    //        }
    //    }
    //}

    var firstid = 0;
    var detaildomId = 1;
    //计算总金额
    function calculateAmount() {
        //按自然月计算，一个月按30天计算，1，用单价（月）除以30天得到单价，2,计算天数，用结束时间减去开始时间，3,用单价乘以数量乘以天数得到总金额
        //按自然天计算，1,用单价乘以数量乘以天数得到总金额

        var unitPrice = $("#UnitPrice").numberbox('getValue');
        var number = $("#Number").numberbox('getValue');
        var beginTime = $("#BeginTime").datebox('getValue');
        var endTime = $("#EndTime").datebox('getValue');
        //var days = (new Date(endTime).getTime() - new Date(beginTime).getTime()) / (1000 * 60 * 60 * 24);

        ////获取包仓算法  1:自然月 2:计费月 3:自然天
        //var storeAlgorithm = $("#StoreAlgorithm").combobox('getValue');
        //if (storeAlgorithm != 3) {

        //    unitPrice = unitPrice / 30;
        //}
        //var amount = unitPrice * number * (days + 1);
        //$("#Amount").numberbox('setValue', amount.toFixed(2));

        //获取包仓算法  1:自然月 2:计费月 3:自然天
        var storeAlgorithm = $("#StoreAlgorithm").combobox('getValue');

        var months = [];
        if (storeAlgorithm == 2) {
            months = dateCutByMonth2(beginTime, endTime);
        } else {
            months = dateCutByMonth(beginTime, endTime);
        }


        var days = 0;
        months.forEach(function (value, index) {
            var day = (new Date(value.endDate).getTime() - new Date(value.beginDate).getTime()) / (1000 * 60 * 60 * 24);
            day = day + 1;
            if (day > 30) {
                day = 30;
            }
            days += day;
        })

        //var days = (new Date(endTime).getTime() - new Date(beginTime).getTime()) / (1000 * 60 * 60 * 24);


        if (storeAlgorithm != 3) {

            unitPrice = unitPrice / 30;
        }
        var amount = unitPrice * number * days;//(days + 1);
        $("#Amount").numberbox('setValue', amount.toFixed(2));


        var contractId= $("#Id").val();
        if (amount > 0) {
            $("tr[id*='detail']").remove();
            //var detail = {};
            //if (detaildomId > 1) {
            //    detail = {
            //        "BeginTime": beginTime,
            //        "EndTime": endTime,
            //        "UnitPrice": unitPrice,
            //        "Number": number,
            //        "TotalPrice": amount.toFixed(2)
            //    };
            //}
            if (firstid == 0) {
                $('#Amount').numberbox('setValue', @Model.Bill.Amount);
                $.post("/LKWarehouseContract/_EditLKWarehouseContractDetail", { ContractId: contractId }, function (html) {
                    $.messager.progress('close');
                    $("#detailgird").append(html);
                    $.parser.parse($("tr[id*='detail']"));
                    detaildomId = Number(detaildomId) + 1;

                    firstid++;

                    initDom();
                });
            } else {
                var details = [];
                months.forEach(function (value, index) {
                    var detailUnitPrice = $("#UnitPrice").numberbox('getValue');
                    var day = (new Date(value.endDate).getTime() - new Date(value.beginDate).getTime()) / (1000 * 60 * 60 * 24);
                    day = day + 1;
                    if (day > 30) {
                        day = 30;
                    }
                    if (storeAlgorithm != 3) {

                        detailUnitPrice = detailUnitPrice / 30;
                    }
                    var detailamount = detailUnitPrice * number * day;
                    var detail = {
                        "BeginTime": value.beginDate,
                        "EndTime": value.endDate,
                        "UnitPrice": $("#UnitPrice").numberbox('getValue'),
                        "Number": number,
                        "TotalPrice": detailamount.toFixed(2)
                    };
                    details.push(detail);
                });
                $.post("/LKWarehouseContract/_AddLKWarehouseContractDetail", { DetailDomId: detaildomId, DetailList: details }, function (html) {
                    $.messager.progress('close');
                    $("#detailgird").append(html);

                    //$.parser.parse($("#detail" + detaildomId));
                    detaildomId = Number(detaildomId) + 1;
                    initDom();
                });
            }
        }
    }


    //计算金额
    function calculateAmount2() {
        initDom();

        var totalAmount = 0.00;
        detaildom.forEach(function (value, index) {
            var i = value;
            var totalprice = $("#TotalPrice" + i).numberbox('getValue') * 1;
            totalAmount += totalprice;
        });
        $("#Amount").numberbox('setValue', totalAmount);
    }

</script>
<link href="~/Content/css/custome.css" rel="stylesheet" />
<div title="编辑包仓合同" style="width:auto; height:auto; padding-left:5px; font-size:14px;  ">
    <div class="ftitle">
        @if (Model.Bill.Status == (int)Gx.Model.Enums.EntryBillStatus.Submitted)
        {
            <a href="javascript:" class="easyui-linkbutton" iconCls="icon-ok" style="height:32px" onclick="editLKWarehouseContract()">保存</a>
        }
        <a href="/LKWarehouseContract/LKWarehouseContractList" class="easyui-linkbutton" iconCls="icon-back" style="height:32px">返回</a>
    </div>
    <form id="fm" method="post" novalidate>
        <input type="hidden" id="Id" value="@Model.Bill.Id" />
        <input type="hidden" id="IsValid" value="@Model.Bill.IsValid.ToString()" />
        <div class="ftitle">基础信息</div>
        <div class="fitem1">
            <label>
                合同编号:
            </label>
            <input class="easyui-textbox" id="ContractNo" name="ContractNo" value="@Model.Bill.ContractNo" style="width: 173px; height: 30px;" readonly="readonly">
            <label>
                客户:
            </label>
            <select class="easyui-combobox" id="CustomerId" style="width: 173px; height: 30px;" data-options="editable: false,prompt:'客户;'"></select>
            <label>
                客户名称:
            </label>
            <input name="CustomerName" id="CustomerName" class="easyui-textbox" style="width: 173px; height: 30px;" value="@Model.Bill.CustomerName" />
        </div>
        <div class="fitem1">
            <label>
                开单日期:
            </label>
            <input id="ContractTime" name="ContractTime" value="@Model.Bill.ContractTime.ToString("yyyy-MM-dd")" class="easyui-datebox" style="width: 173px; height: 30px;" />
            <label>
                开始日期:
            </label>
            <input id="BeginTime" name="BeginTime" value="@Model.Bill.BeginTime.ToString("yyyy-MM-dd")" class="easyui-datebox" style="width: 173px; height: 30px;" data-options="required:true,onChange:calculateAmount" />
            <label>
                结束日期:
            </label>
            <input id="EndTime" name="EndTime" value="@Model.Bill.EndTime.ToString("yyyy-MM-dd")" class="easyui-datebox" style="width: 173px; height: 30px;" data-options="required:true,onChange:calculateAmount" />
        </div>
        <div class="fitem1">
            <label>
                包仓类型:
            </label>
            <select class="easyui-combobox" id="StoreType" style="width: 173px; height: 30px;" data-options="required:true"></select>
            <label>
                包仓算法:
            </label>
            <select class="easyui-combobox" id="StoreAlgorithm" style="width: 173px; height: 30px;" data-options="required:true,onChange:calculateAmount"></select>
            <label>
                单价:
            </label>
            <input id="UnitPrice" name="UnitPrice" value="@Model.Bill.UnitPrice" class="easyui-numberbox" data-options="required: true,precision:'2',onChange:calculateAmount" style="width: 173px; height: 30px;" />
        </div>
        <div class="fitem1">
            <label>
                数量:
            </label>
            <input id="Number" value="@Model.Bill.Number" class="easyui-numberbox" data-options="required: true,onChange:calculateAmount" style="width: 173px; height: 30px;" />
            <label>
                总金额:
            </label>
            <input id="Amount" name="Amount" value="@Model.Bill.Amount" class="easyui-numberbox" data-options="precision:'2',prompt:'总金额'" style="width: 173px; height: 30px;" readonly="readonly" />
            <label>
                按吨操作:
            </label>
            <input class="easyui-switchbutton" id="sbIsByTon" value="@Model.Bill.IsByTon" data-options="onText:'是',offText:'否'">
        </div>
        <div class="fitem1">
            <label>
                仓库;:
            </label>
            <select class="easyui-combobox" id="WareHouseId" style="width: 173px; height: 30px;" data-options="editable: false,prompt:'仓库;'"></select>
        </div>
        <div class="fitem1">
            <label>
                图片:
            </label>
            <input type="hidden" id="hidFileId" />
            <input id="filebox" class="easyui-filebox" name="file" data-options="buttonText:'选择文件',accept:'image/*',onChange:fileChange" /><a href="@Model.FilePath" target="_blank">@Model.FileName</a>
        </div>
        <div class="fitem1">
            <label>
                备注:
            </label>
            <textarea rows="4" cols="4" style="width: 400px; height: 90px; vertical-align: top" name="Remark" id="Remark" autocomplete="off" placeholder="200字以内">@Model.Bill.Remark</textarea>
        </div>
        <div id="Wl">
            <div id="tabs" class="easyui-tabs" fit="true" border="false" style="width:500px;height:300px;">
                <div title="包仓明细">
                    @*<input id="DetailDomNum" type="hidden" value="@(Model.DetailList.Count+1)" />
                    @{
                        int di = 1;
                    }*@
                    <table class="gridtable" id="detailgird">
                        <thead>
                            <tr>
                                <th>开始日期</th>
                                <th>结束日期</th>
                                <th>单价</th>
                                <th>数量</th>
                                <th>原金额</th>
                                <th>总金额</th>
                                <th>已结算</th>
                                <th>是否收费</th>
                            </tr>

                        </thead>
                    </table>

                </div>
                <div title="默认杂费设置">
                    <input id="DomNum" type="hidden" value="@(Model.CostList.Count+1)" />
                    @{
                        int i = 1;
                    }
                    <a href="javascript:" class="easyui-linkbutton" iconcls="icon-add" plain="true" onclick="addDom()">添加</a>
                    <input type="hidden" id="deletecostid" />
                    <table class="gridtable" id="costgird">
                        <thead>
                            <tr>
                                <th>费用类别</th>
                                <th>价格</th>
                                <th>单位</th>
                                <th>在入库单显示</th>
                                <th>在出库单显示</th>
                                <th>在调仓单显示</th>
                                <th>操作</th>
                            </tr>
                            @foreach (var item in Model.CostList)
                            {
                                <tr id="@i">
                                    <td>
                                        <input class="easyui-combobox" id="@("CostType")@i" value="@item.CostType" style="width: 173px; height: 30px;" />
                                        <input type="hidden" id="@("DomId")@i" value="@i" />
                                        <input type="hidden" id="@("CostId")@i" value="@item.Id" />
                                        <input type="hidden" id="@("ContractId")@i" value="@item.ContractId" />
                                        <input type="hidden" id="@("ContractType")@i" value="@item.ContractType" />
                                    </td>
                                    <td><input id="@("Price")@i" class="easyui-numberbox" value="@item.Price" data-options="precision:'2',prompt:'价格'" style="width: 80px; height: 30px;" /></td>
                                    <td><input class="easyui-textbox" id="@("Unit")@i" value="@item.Unit" style="width: 173px; height: 30px;"></td>
                                    <td><input class="easyui-switchbutton" id="@("sbInStorage")@i" data-options="onText:'是',offText:'否'"></td>
                                    <td><input class="easyui-switchbutton" id="@("sbOutStorage")@i" data-options="onText:'是',offText:'否'"></td>
                                    <td><input class="easyui-switchbutton" id="@("sbTransferStorage")@i" data-options="onText:'是',offText:'否'"></td>
                                    <td><a href="javascript:" class="easyui-linkbutton" iconcls="icon-no" plain="true" style=" width:80px;" onclick="delDom(@i)">删除</a></td>
                                </tr>
                                i++;
                            }
                        </thead>
                    </table>
                    @{
                        i = 1;
                    }
                    @foreach (var item in Model.CostList)
                    {
                        <script type="text/javascript">
        $(function () {
            //InitCombogrid('@i', '@item');
            $('@("#sbInStorage")@i').switchbutton({ checked: @Html.Raw(item.InStorage ? "true" : "false") });
            $('@("#sbOutStorage")@i').switchbutton({ checked: @Html.Raw(item.OutStorage ? "true" : "false") });
            $('@("#sbTransferStorage")@i').switchbutton({ checked: @Html.Raw(item.TransferStorage ? "true" : "false") });
        });
                        </script>
                        i++;
                    }
                </div>
            </div>
        </div>
        <div class="fitem1">
            @{
                var modifyuser = Model.Bill.ModifyUserId == 0 ? Gx.Dal.Shared.UserContext.CurrentUser.EmpName : Model.Bill.ModifyUser;
                var modifytime = Model.Bill.ModifyTime.ToString("yyyy-MM-dd") == "1911-01-01" ? "" : Model.Bill.ModifyTime.ToString("yyyy-MM-dd");
            }
            <label>
                制单人:
            </label>
            <label>
                @Model.Bill.CreateUser
            </label>

            <label>
                制单日期:
            </label>
            <label>
                @Model.Bill.CreateTime.ToString("yyyy-MM-dd")
            </label>
            <label>
                修改人:
            </label>
            <label>
                @modifyuser
            </label>
            <label>
                修改日期:
            </label>
            <label>
                @modifytime
            </label>
        </div>
    </form>
</div>











